<?php
class PeopleSignsController extends AppController {

	var $name = 'PeopleSigns';
	var $uses = array('PeopleSign','Person','Sign');

    function beforeFilter () {
        parent::beforeFilter();

		// Aplico el Layout segun la Vista o si es AJAX
		if ($this->RequestHandler->isAjax()) {
			$this->layout = 'ajax';
		}else{
			// Cambio la Vista por la del Rol
			$this->layout = strtolower($this->Session->read('VistaActual'));
		}
    }
    
	function index($id_paciente = null, $archivados = null) {
		$this->PeopleSign->recursive = 0;

		if(!$archivados){
			$peopleSigns = $this->PeopleSign->find('all', array(
							'conditions' => array(
												'PeopleSign.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleSign.person_id' => $id_paciente,
												'NOT' => array ('PeopleSign.staterecord_id' => array('2','3'))
											),
							'fields' => array('PeopleSign.id, PeopleSign.person_id, PeopleSign.fecha, PeopleSign.valor, Sign.id, Sign.name'),
							'order' => array('PeopleSign.fecha DESC')
			) );
		}else{ // Para mostrar tambien los registros ARCHIVADOS
			$peopleSigns = $this->PeopleSign->find('all', array(
							'conditions' => array(
												'PeopleSign.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleSign.person_id' => $id_paciente,
												'NOT' => array ('PeopleSign.staterecord_id' => array('2'))
											),
							'fields' => array('PeopleSign.id, PeopleSign.person_id, PeopleSign.fecha, PeopleSign.valor, Sign.id, Sign.name'),
							'order' => array('PeopleSign.fecha DESC')
			) );
		}
		$this->set('archivados', $archivados);


		$this->set('peopleSigns', $peopleSigns);
		$this->set('id_paciente', $id_paciente);
		$this->layout = 'ajax';
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid people sign', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('peopleSign', $this->PeopleSign->read(null, $id));
	}

	function add($id_paciente = null) {

		if (!empty($this->data)) {

			foreach($this->data['PeopleSign']['valor'] AS $indice => $valor_signo){

				// Si se cargo el Valor del Signo
				if($valor_signo <> ""){

					$this->PeopleSign->create();

					// Seteo datos que no vienen del Formulario
					$this->PeopleSign->set(array(
						'client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
						'user_id' => $this->Auth->user('id'),
						'fecha' => $this->data['fecha'][$indice]['year']."-".$this->data['fecha'][$indice]['month']."-".$this->data['fecha'][$indice]['day']." ".$this->data['fecha'][$indice]['hour'].":".$this->data['fecha'][$indice]['min'],
						'valor' => $valor_signo,
						'person_id' => $this->data['PeopleSign']['person_id'],
						'sign_id' => $this->data['PeopleSign']['sign_id'][$indice],

					));

					// Grabo cada Signo
					if ($this->PeopleSign->save()) {
						$this->Session->setFlash(__('El Signo Vital a sido asociado', true));
					} else {
						$this->Session->setFlash(__('El Signo Vital no ha podido ser asociado. Por favor, intente luego.', true));
					}

				}
			}


			// Consulto la ultima altura del Paciente
			$arreglo_altura = $this->requestAction('/signs/ultimosigno/11/'.$this->data['PeopleSign']['person_id']);
			$ultima_altura = $arreglo_altura['valor'];
			$fecha_ultima_altura = $arreglo_altura['fecha'];

			// Consulto el ultimo peso del Paciente
			$arreglo_peso = $this->requestAction('/signs/ultimosigno/10/'.$this->data['PeopleSign']['person_id']);
			$ultimo_peso = $arreglo_peso['valor'];

			// Actualizo el Signo Indice de Masa Corporal (Peso / Altura al cuadrado) si se cargo la Altura y el Peso
			if($ultima_altura != "" AND $ultima_altura != 0){
				$imc = ($ultimo_peso / ($ultima_altura * $ultima_altura)) * 10000;

				if($imc > 0){

					$this->PeopleSign->create();

					$this->PeopleSign->set(array(
						'client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
						'user_id' => $this->Auth->user('id'),
						'fecha' => $fecha_ultima_altura,
						'valor' => $imc,
						'person_id' => $this->data['PeopleSign']['person_id'],
						'sign_id' => 15,
					));

					// Grabo el Signo IMC
					$this->PeopleSign->save();
				}
			}

			$this->redirect('/people/view/'.$this->data['PeopleSign']['person_id'].'/4');
			exit;
		}

		if (!$id_paciente) {
			exit;
		}
	
		// Acorto la Busqueda
		$this->Sign->unBindModel(array(hasAndBelongsToMany => array('Person')));

		$signs = $this->Sign->find('all', array(
						'conditions' => array(
											'NOT' => array ('Sign.id' => array('15'))
										),
						'fields' => array('Sign.name','Sign.unidad','Sign.id'),
						'order' => array('Sign.orden')
		)) ;
		

		$this->set('id_paciente', $id_paciente);
		$this->set(compact('signs'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid people sign', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->PeopleSign->save($this->data)) {
				$this->Session->setFlash(__('The people sign has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The people sign could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->PeopleSign->read(null, $id);
		}
		$people = $this->PeopleSign->Person->find('list');
		$clients = $this->PeopleSign->Client->find('list');
		$signs = $this->PeopleSign->Sign->find('list');
		$this->set(compact('people', 'clients', 'signs'));
	}

	function archivar($id = null, $id_paciente = null, $estado = null) {
		if (!$id) {
			$this->Session->setFlash(__('Signo Vital no valido', true));
			$this->redirect('/dashboards');
		}

		if (!$id_paciente) {
			$this->Session->setFlash(__('Paciente no valido', true));
			$this->redirect('/dashboards');
		}

		if (!$estado) {
			$this->Session->setFlash(__('Estado no valido', true));
			$this->redirect('/dashboards');
		}

		$this->PeopleSign->id = $id;
		$this->PeopleSign->set(array(
			'staterecord_id' =>  $estado,
			'user_id' => $this->Auth->user('id'),
		));

		if ($this->PeopleSign->save()) {
			$this->Session->setFlash(__('El Signo Vital fue procesado.', true));
			$this->redirect('/people/view/'.$id_paciente.'/4');
		}
		$this->Session->setFlash(__('El Signo Vital no pudo serp rocesado', true));
		$this->redirect('/people/view/'.$id_paciente.'/4');
	}
}
?>